package com.ebt.m.utils;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * Created by archer.qi on 2016/6/8.
 */
public class ImageSelectUtil {

    /**
     * 拍照
     *
     * @param context
     * @param savF
     * @param requestCode
     */
    public static void openCamera(Activity context, File savF, int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri = UriUtils.getUriFromFile(savF);
        if (savF != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        context.startActivityForResult(intent, requestCode);
    }


    /**
     * 从相册选择
     *
     * @param context
     * @param requestCode
     */
    public static void openAlbum(Activity context, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 从相册选择
     *
     * @param context
     * @param requestCode
     */
    public static void openAlbum(Activity context, File target, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        Uri uri = UriUtils.getUriFromFile(target);
        if (target != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 从相册选择
     *
     * @param fragment
     * @param requestCode
     */
    public static void openAlbum(Fragment fragment, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        fragment.startActivityForResult(intent, requestCode);
    }

    /**
     * 从相册选择
     *
     * @param context
     * @param requestCode
     */
    public static void openCroppedAlbum(Activity context, File target, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("outputX", 480);
        intent.putExtra("outputY", 800);
        intent.putExtra("return-data", true);
        Uri uri = UriUtils.getUriFromFile(target);
        if (target != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG);
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 拍照 - > 裁剪
     *
     * @param context
     */
    public static void crop(Activity context, File target, Uri uri, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.putExtra("scale", true);
        intent.putExtra("crop", "true");

        intent.putExtra("outputX", 480);
        intent.putExtra("outputY", 800);

        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, UriUtils.getUriFromFile(target));
        context.startActivityForResult(intent, requestCode);
    }


    /**
     * 获取拍照缓存路径
     *
     * @return
     */
    public static String getImageCacheDir() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            String sdPath = Environment.getExternalStorageDirectory().getPath();
            String cacheDir = "Camera";
            return sdPath + "/" + cacheDir;
        }
        return null;
    }

    /**
     * 获取图片名
     *
     * @param type
     * @return
     */
    public static String getFileName(int type, String suffix) {
        // 时间戳
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmmss",
                Locale.CHINA);
        String dateTemp = formater.format(System.currentTimeMillis());
        // 类型
        String cacheType = getImageType(type);
        // 后缀名
        String defaultSuffix = ".jpg";

        if (TextUtils.isEmpty(suffix)) {
            suffix = defaultSuffix;
        }

        return dateTemp + cacheType + suffix;
    }

    /**
     * 获取图片缓存类型
     *
     * @param type
     * @return
     */
    public static String getImageType(int type) {
        String mIMAG_TYPE = "";

        switch (type) {
            case 0:
                mIMAG_TYPE = "_camera";
                break;
            case 1:
                mIMAG_TYPE = "_album";
                break;
            case 2:
                mIMAG_TYPE = "_common";
                break;
            default:
                break;
        }

        return mIMAG_TYPE;
    }

    /**
     * 根据路径得到一个可用文件
     *
     * @param dir
     * @param name
     * @return
     */
    public static File getFile(String dir, String name) {
        if (TextUtils.isEmpty(dir) || TextUtils.isEmpty(name)) {
            return null;
        }

        File dirF = new File(dir);
        if (!dirF.exists()) {
            dirF.mkdirs();
        }

        String path = dir + "/" + name;
        File file = new File(path);

        return file;
    }

    /**
     * 获取拍照图片的旋转角度
     *
     * @param path
     * @return
     */
    public static int getPhotoDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 根据指定角度旋转图片
     *
     * @param angle
     * @param bitmap
     * @return
     */
    public static Bitmap rotateImage(int angle, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    /**
     * 保存bitmap
     *
     * @param bmp
     * @param path
     */
    public static void saveBitmap(Bitmap bmp, String path) {
        if (bmp == null || TextUtils.isEmpty(path)) {
            return;
        }

        String dir = path.substring(0, path.lastIndexOf("/"));
        String fileName = path.substring(path.lastIndexOf("/") + 1);

        saveBitmap(bmp, fileName, dir, 100);
    }

    /**
     * 保存Bitmap
     *
     * @param bitmap
     * @param fileName
     * @param dir
     * @param quality  压缩尺度, 100为不压缩
     * @throws IOException
     */
    public static void saveBitmap(Bitmap bitmap, String fileName, String dir,
                                  int quality) {

        if (bitmap == null || TextUtils.isEmpty(dir)
                || TextUtils.isEmpty(fileName)) {
            throw new NullPointerException(
                    "NullException: bitmap is null or dir, fileName is null!");
        }

        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        File file = new File(dir, fileName);
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, quality, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据Uri获取图片路径
     *
     * @param activity
     * @param uri
     * @return
     */
    public static String getPathFromUri(Activity activity, Uri uri) {
        if (TextUtils.isEmpty(uri.toString())) {
            return null;
        }
        if (uri.toString().startsWith("file:")) {
            if (uri.toString().length() >= 8) {
                return uri.toString().substring(7);
            } else {
                return null;
            }
        }

        String[] projection = {MediaStore.MediaColumns.DATA};
        Cursor cursor = activity
                .managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(column_index);
            return path;
        }
        return null;
    }


}
